﻿using DongFangGuoKai.WCSPlatform.WebApi.Extensions;
using DongFangGuoKai.WCSPlatform.WebApi.Logs;
using DongFangGuoKai.WCSPlatform.WebApi.Utils.UtilModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Data.Entity;
using System.Data.Entity.SqlServer;
using System.IO.Compression;

namespace DongFangGuoKai.WCSPlatform.WebApi.Controllers
{
    /// <summary>
    /// WCS日志查询
    /// </summary>
    [Route("api/[controller]/[action]"), ApiController]
    public class LogController : ControllerBase
    {
        private readonly ISqlSugarClient client;
        private readonly Logs.DbContext context;
        private readonly ILogger<LogController> logger;
        private readonly IWebHostEnvironment webHostEnvironment;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="client"></param>
        public LogController(ISqlSugarClient client, Logs.DbContext context,ILogger<LogController> logger, IWebHostEnvironment webHostEnvironment)
        {
            this.client = client;
            this.context = context;
            this.logger = logger;
            this.webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="Level">等级</param>
        /// <param name="msg">消息</param>
        /// <param name="time">时间</param>
        /// <param name="funName">方法名</param>
        /// <param name="className">类名</param>
        /// <param name="classNameNo">类名</param>
        /// <param name="funNameNo">类名</param>
        /// <param name="msgNo">类名</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<WCSApiResponse> GetLog(string? Level, string? time,string? className,string? funName,string? msg, string? classNameNo, string? funNameNo, string? msgNo, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var list = client.Queryable<LogModel>()
                          .WhereIF(!string.IsNullOrEmpty(Level), s => string.Equals(s.Level, Level, StringComparison.OrdinalIgnoreCase))
                          .WhereIF(!string.IsNullOrEmpty(className), s => s.Logger.Contains(className, StringComparison.OrdinalIgnoreCase))
                          .WhereIF(!string.IsNullOrEmpty(funName), s => s.Callsite.Contains(funName, StringComparison.OrdinalIgnoreCase))
                          .WhereIF(!string.IsNullOrEmpty(time),s => s.Logged.ToString().Contains(time, StringComparison.OrdinalIgnoreCase))
                          .WhereIF(!string.IsNullOrEmpty(msg),s=>s.Message.Contains(msg, StringComparison.OrdinalIgnoreCase))
                           .WhereIF(!string.IsNullOrEmpty(classNameNo), s => !s.Logger.Contains(classNameNo, StringComparison.OrdinalIgnoreCase))
                            .WhereIF(!string.IsNullOrEmpty(funNameNo), s => !s.Callsite.Contains(funNameNo, StringComparison.OrdinalIgnoreCase))
                            .WhereIF(!string.IsNullOrEmpty(msgNo), s => !s.Message.Contains(msgNo, StringComparison.OrdinalIgnoreCase))
                          .OrderByDescending(s => s.Logged);
                var pageList = list.ToPageList(pageIndex, pageSize);
                return this.Success(new { pageList, count = list.Count() });

            }
            catch (Exception ex)
            {
                return this.Fail(ex.Message);
            }
        }
        [HttpGet]
        public ActionResult<WCSApiResponse> GetLogByDbContext(int pageIndex,int pageSize)
        {
            var pageModel = new PageModel()
            {
                PageIndex = pageIndex,
                PageSize = pageSize
            };
            return this.Success(new 
            {
                list = context.LogModel.GetPageList(s => true, pageModel),
                pageModel.TotalCount
            });
        }
        /// <summary>
        /// 删除指定id
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete]
        public ActionResult<WCSApiResponse> DelLogById(int[]? ids)
        {
            try
            {
                var delRes = client.Deleteable<LogModel>().In(ids).ExecuteCommand();
                if (delRes > 0)
                {
                    logger.LogInformation($"[{string.Join(',', ids)}]的日志被删除");
                    return this.Success(delRes);
                }
                return this.Fail("删除失败");
            }
            catch (Exception ex)
            {
                return this.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 删除全部
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public ActionResult<WCSApiResponse> DelLog()
        {
            try
            {
                var delRes = client.Deleteable<LogModel>().ExecuteCommand();

                return this.Success(delRes);
            }
            catch (Exception ex)
            {
                return this.Fail(ex.Message);
            }
        }

        /// <summary>
        /// 下载日志
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult DownloadWCSLogs()
        {
            string folderPath = Path.Combine(webHostEnvironment.ContentRootPath, "Logs");

            if (Directory.Exists(folderPath))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                    {
                        DirectoryInfo directory = new DirectoryInfo(folderPath);

                        foreach (FileInfo file in directory.GetFiles())
                        {
                            if (file.Name != "DbContext.cs" && file.Name != "LogModel.cs")
                            {
                                using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                                {
                                    ZipArchiveEntry entry = archive.CreateEntry(file.Name);

                                    using (Stream entryStream = entry.Open())
                                    {
                                        fileStream.CopyTo(entryStream);
                                    }
                                }
                            }
                        }

                    }

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    byte[] bytes = memoryStream.ToArray();
                    return File(bytes, "application/zip", "Logs.zip");
                }
            }
            else
            {
                return NotFound();
            }
        }

    }





}
//.OrderByDescending(s => s.Logged).Mapper(s => 
//{
//    s.Logged = new DateTime(s.Logged.Year, s.Logged.Month, s.Logged.Day, s.Logged.Hour, s.Logged.Minute, s.Logged.Second);
//});